<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-14
 * Time: 16:09:46
 * Info: 博客动态
 */

namespace plugin\huiblog\app\controller;

use support\Request;
use think\facade\Db;
use plugin\huiblog\app\model\Action as ActionModel;

class ActionController
{

    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $limit = (int)$request->input('limit', 15);
            $page  = (int)$request->input('page', 1);
            $key   = $request->input('key');
            $first = ($page - 1) * $limit;

            $where = function ($query) use ($key) {
                if ( ! empty($key['content'])) {
                    $query->whereLike('content', "%".$key['content']."%");
                }
            };
            $count = ActionModel::where($where)->count();
            $data  = ActionModel::where($where)->limit($first, $limit)->order('id desc')->select()->toArray();

            return json(['code' => 0, 'count' => $count, 'data' => $data, 'msg' => 'ok']);
        }

        return view('admin/action/index');
    }

    public function add(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['content'])) {
                return json(['code' => 0, 'msg' => '内容不能为空']);
            }
            $param['thumbs'] = ! empty($param['thumbs']) ? json_encode($param['thumbs'], true) : "";
            ActionModel::create($param);

            return json(['code' => 200, 'msg' => '操作成功']);
        }

        return view('admin/action/add');
    }

    public function edit(Request $request)
    {
        $id = $request->get('id');
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['id'])) {
                return json(['code' => 0, 'msg' => '参数错误']);
            }
            if (empty($param['content'])) {
                return json(['code' => 0, 'msg' => '内容不能为空']);
            }
            $param['thumbs'] = ! empty($param['thumbs']) ? json_encode($param['thumbs'], true) : "";
            ActionModel::update($param, ['id' => $param['id']]);

            return json(['code' => 200, 'msg' => '操作成功']);
        }
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        $data           = ActionModel::find($id);
        $data['thumbs'] = json_decode($data['thumbs'], true) ?? [];

        if (empty($data)) {
            return json(['code' => 0, 'msg' => '获取数据失败']);
        }

        return view('admin/action/edit', ['data' => $data]);

    }

    public function delete(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        ActionModel::where('id', $id)->delete();

        return json(['code' => 200, 'msg' => '删除成功']);
    }

}